package com.walker.kuyun.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.walker.kuyun.App
import com.walker.kuyun.R
import com.walker.kuyun.bean.*
import com.walker.kuyun.config.Api
import com.walker.kuyun.config.Const
import com.walker.kuyun.ui.adapter.SerializableRecycledViewPool
import com.walker.kuyun.util.JsoupUtil
import com.walker.kuyun.util.ParseHtmlUtil.parseDnews
import com.walker.kuyun.util.ParseHtmlUtil.parseHeroWrap
import com.walker.kuyun.util.ParseHtmlUtil.parseImg
import com.walker.kuyun.util.ParseHtmlUtil.parseLpic
import com.walker.kuyun.util.ParseHtmlUtil.parseNextPages
import com.walker.kuyun.util.ParseHtmlUtil.parseTopli
import com.walker.kuyun.util.Util.showToastOnThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jsoup.select.Elements
import java.util.*


class TMShowViewModel : ViewModel() {
    var childViewPool: SerializableRecycledViewPool? = null
    var viewPool: SerializableRecycledViewPool? = null
    var videoShowList: MutableList<VideoShowBean> = ArrayList()
    var mldGetAnimeShowList: MutableLiveData<Int> = MutableLiveData()   // value：-1错误；0重新获取；1刷新
    var pageNumberBean: PageNumberBean? = null
    var newPageIndex: Pair<Int, Int>? = null

    private var isRequesting = false

    fun getAnimeShowData(partUrl: String, isRefresh: Boolean = true) {
        viewModelScope.launch(Dispatchers.IO) {
            //if (!partUrl.contains("/vod/type/id/1.html")) return@launch
            try {
                if (isRequesting) return@launch
                isRequesting = true
                pageNumberBean = null
                val url = Api.MAIN_URL + partUrl
                val document = JsoupUtil.getDocument(url)
//                hot search
//                document.getElementsByClass("fed-pops-hot").apply {
//                    Log.d("TestCap", "getAnimeShowData: " + this.text())
//                    // li class=fed-col-xs6
//                }

                //li
                document.getElementsByClass("fed-list-pics fed-part-5by2 fed-swip-lazy").apply {
                    val bannerItemList = ArrayList<VideoCoverBean>()
                    for (element in this) {
                        val img: String = element.attr("data-background").let {
                            if (it.startsWith("http")) it
                            else Api.MAIN_URL + it
                        }
                        val href = element.attr("href")
                        val desc = element.getElementsByClass("fed-part-eone fed-font-xii").text()
                        val text = element.text()
                        val cover = VideoCoverBean(
                            Const.ViewHolderTypeString.ITEM_COVER_6, href, Api.MAIN_URL + href,
                            text, ImageBean("", "", img, img),
                            "", null, desc,
                            TMEpisodeDataBean("", "", ""),
                            null,
                            null
                        )
                        bannerItemList.add(cover)
                    }
                    videoShowList.add(
                        VideoShowBean(
                            Const.ViewHolderTypeString.BANNER_1, "",
                            "", "", "", "", "",
                            bannerItemList
                        )
                    )
                }
                //div
                document.getElementsByClass("fed-part-layout fed-back-whits").apply {
                    for (element in this) {
                        val title = element.getElementsByClass("fed-font-xvi").text()
                        videoShowList.add(
                            VideoShowBean(
                                Const.ViewHolderTypeString.HEADER_1,
                                "",
                                "",
                                title,
                                "",
                                "",
                                ""
                            )
                        )
                        val content =
                            element.getElementsByClass("fed-list-item fed-padding fed-col-xs4 fed-col-sm3 fed-col-md2")
                        val tmpList = ArrayList<VideoCoverBean>()
                        for (c in content) {
                            val itemImg =
                                c.getElementsByClass("fed-list-pics fed-lazy fed-part-2by3")
                                    .attr("data-original").toString().let {
                                        if (it.startsWith("http")) it
                                        else Api.MAIN_URL + it
                                    }
                            val href = c.getElementsByClass("fed-list-pics fed-lazy fed-part-2by3")
                                .attr("href")
                            val episode =
                                c.getElementsByClass("fed-list-remarks fed-font-xii fed-text-white fed-text-center")
                                    .text()
                            val itemTxt =
                                c.getElementsByClass("fed-list-title fed-font-xiv fed-text-center fed-text-sm-left fed-visible fed-part-eone")
                                    .text()
                            tmpList.add(
                                VideoCoverBean(
                                    Const.ViewHolderTypeString.ITEM_COVER_1,
                                    href,
                                    Api.MAIN_URL + href,
                                    itemTxt,
                                    ImageBean("", "", itemImg, itemImg),
                                    episode,
                                    score = c.getElementsByClass("fed-list-score fed-font-xii fed-back-green")
                                        .text().toFloat()
                                )
                            )
                        }
                        val itemContainer = VideoShowBean(
                            Const.ViewHolderTypeString.GRID_LIST_1,
                            "", "", "", "", "", "",
                            tmpList
                        )
                        videoShowList.add(itemContainer)
                    }

                }
                if (true) {
                    newPageIndex = Pair(0, videoShowList.size)
                    mldGetAnimeShowList.postValue(if (isRefresh) 0 else 1)
                    isRequesting = false
                    return@launch
                } else return@launch
                if (isRefresh) videoShowList.clear()
                val positionStart = videoShowList.size
                //banner
                val foucsBgElements: Elements = document.getElementsByClass("foucs bg")
                for (i in foucsBgElements.indices) {
                    val foucsBgChildren: Elements = foucsBgElements[i].children()
                    for (j in foucsBgChildren.indices) {
                        when (foucsBgChildren[j].className()) {
                            "hero-wrap" -> {
                                videoShowList.add(
                                    VideoShowBean(
                                        Const.ViewHolderTypeString.BANNER_1, "",
                                        "", "", "", "", "",
                                        parseHeroWrap(foucsBgChildren[j], url)
                                    )
                                )
                            }
                        }
                    }
                }
                //area
                var area: Elements = document.getElementsByClass("area")
                if (partUrl == "/") //首页，有右边栏
                    area = document.getElementsByClass("area").select("[class=firs l]")
                for (i in area.indices) {
                    val elements: Elements = area[i].children()
                    for (j in elements.indices) {
                        when (elements[j].className()) {
                            "dtit" -> {
                                val a = elements[j].select("h2").select("a")
                                if (a.size == 0) {      //只有一个标题
                                    videoShowList.add(
                                        VideoShowBean(
                                            Const.ViewHolderTypeString.HEADER_1,
                                            "",
                                            "",
                                            elements[j].select("h2").text(),
                                            "",
                                            "",
                                            ""
                                        )
                                    )
                                } else {        //有右侧“更多”
                                    videoShowList.add(
                                        VideoShowBean(
                                            Const.ViewHolderTypeString.HEADER_1,
                                            a.attr("href"),
                                            Api.MAIN_URL + a.attr("href"),
                                            a.text(),
                                            elements[j].select("span").select("a").text(),
                                            "",
                                            ""
                                        )
                                    )
                                }
                            }
                            "img", "imgs" -> {
                                videoShowList.add(
                                    VideoShowBean(
                                        Const.ViewHolderTypeString.GRID_LIST_1,
                                        "", "", "", "", "", "",
                                        parseImg(elements[j], url)
                                    )
                                )
                            }
                            "fire l" -> {       //右侧前半tab内容
                                val firsLChildren = elements[j].children()
                                for (k in firsLChildren.indices) {
                                    when (firsLChildren[k].className()) {
                                        "lpic" -> {
                                            videoShowList.add(
                                                VideoShowBean(
                                                    Const.ViewHolderTypeString.GRID_LIST_1,
                                                    "", "", "", "", "", "",
                                                    parseLpic(firsLChildren[k], url)
                                                )
                                            )
                                        }
                                        "pages" -> {
                                            pageNumberBean = parseNextPages(firsLChildren[k])
                                        }
                                    }
                                }
                            }
                            "dnews" -> {       //右侧后半tab内容，cover4
                                videoShowList.add(
                                    VideoShowBean(
                                        Const.ViewHolderTypeString.GRID_LIST_1,
                                        "", "", "", "", "", "",
                                        parseDnews(elements[j], url)
                                    )
                                )
                            }
                            "topli" -> {       //右侧后半tab内容，cover5
                                videoShowList.add(
                                    VideoShowBean(
                                        Const.ViewHolderTypeString.GRID_LIST_1,
                                        "", "", "", "", "", "",
                                        parseTopli(elements[j])
                                    )
                                )
                            }
                            "pages" -> {
                                pageNumberBean = parseNextPages(elements[j])
                            }
                        }
                    }
                }
                newPageIndex = Pair(positionStart, videoShowList.size - positionStart)
                mldGetAnimeShowList.postValue(if (isRefresh) 0 else 1)
                isRequesting = false
            } catch (e: Exception) {
                videoShowList.clear()
                mldGetAnimeShowList.postValue(-1)
                isRequesting = false
                e.printStackTrace()
                (App.getApp()
                    .getString(R.string.get_data_failed) + "\n" + e.message).showToastOnThread()
            }
        }
    }

    companion object {
        const val TAG = "AnimeShowViewModel"
    }
}